<!-- 新增成本管理 -->
<template>
  <div class="page p20">
    <div class="top">
      <!-- <el-button type="primary">导入excel</el-button> -->
      <el-button type="primary" @click="addFrom">新增</el-button>
      <upload-excel-component
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
        style="display:inline-block"
      />

      <el-upload
        class="fr btn"
        :action="uploadImportAjax.config.url"
        :headers="uploadImportAjax.config.headers"
        name="file"
        :data="uploadImportAjax.config.data"
        ref="uploadImg"
        accept=".xlsx, .xls"
        :show-file-list="false"
        :on-success="uploadImportSuc"
        :on-error="uploadImportFail"
        :before-upload="uploadImportBefore"
      >
        <el-button type="primary">导入Excel</el-button>
      </el-upload>
      <span style="color:red">
        *注：导入时，周期的填写格式必须为"xxxx-xx-xx~xxxx-xx-xx"否则无法识别，要手动选择
      </span>

      <!-- <el-upload
        class="diy-uploadBtn"
        :action="uploadImgAjax.config.url"
        :headers="uploadImgAjax.config.headers"
        name="file"
        :data="upLoadData"
        ref="uploadImg"
        accept=".jpg, .gif, .jpeg, .png"
        :show-file-list="false"
        :on-success="rUploadSuc"
        :on-error="rUploadImgFail"
        :before-upload="upLoadBefore"
      >
        <el-button type="primary" @click="rUploadImgbtn(index)"
          >上传截图</el-button
        >
      </el-upload> -->
    </div>

    <div class="form">
      <div class="mt20">
        <el-upload
          :action="uploadImgAjax.config.url"
          :headers="uploadImgAjax.config.headers"
          :on-remove="handleRemove"
          name="file"
          ref="uploadImg"
          accept=".xlsx, .xls"
          v-if="ajaxData.list && ajaxData.list.length"
          :on-success="rUploadImgSuc"
          :on-error="rUploadImgFail"
          :before-upload="rUploadImgBefore"
        >
          <el-button>上传截图excel</el-button>
        </el-upload>
      </div>
      <el-form ref="form" :model="ajaxData" inline class="mt20">
        <el-form-item
          label="输入核销项目名:"
          class="block"
          v-if="ajaxData.list.length"
          prop="checkName"
          :rules="{
            required: true,
            message: '核销项目名不能为空',
            trigger: 'blur'
          }"
        >
          <el-input
            v-model="ajaxData.checkName"
            placeholder="输入核销项目名"
            style="width:500px;"
          ></el-input>
        </el-form-item>
        <template v-for="(item, index) in ajaxData.list">
          <div :key="index" class="list">
            <el-button type="danger" @click="delFrom(index)"
              >删除<i class="el-icon-delete el-icon--right"></i></el-button
            ><br /><br />
            <el-form-item
              label="周期:"
              :prop="'list.' + index + '.time'"
              :rules="{
                required: true,
                message: '周期不能为空',
                trigger: 'change'
              }"
            >
              <el-date-picker
                v-model="item.time"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item
              label="平台:"
              :prop="'list.' + index + '.platform'"
              :rules="{
                required: true,
                message: '平台不能为空',
                trigger: 'change'
              }"
            >
              <el-select v-model="item.platform" placeholder="请选择平台">
                <el-option
                  v-for="item in platformMap"
                  :key="item"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
              <!-- <el-input
                v-model="item.platform"
                placeholder="输入平台"
                style="width:200px;"
              ></el-input> -->
            </el-form-item>
            <el-form-item
              label="币别:"
              :prop="'list.' + index + '.coinType'"
              :rules="{
                required: true,
                message: '币别不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.coinType"
                placeholder="输入币别"
                style="width:100px;"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="平台账号:"
              :prop="'list.' + index + '.platformAccount'"
              :rules="{
                required: item.rechargeType == '线上',
                message: '平台账号不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.platformAccount"
                placeholder="输入平台账号"
                style="width:300px;"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="运营姓名:"
              :prop="'list.' + index + '.username'"
              :rules="{
                required: true,
                message: '运营姓名不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.username"
                placeholder="输入姓名"
                style="width:130px;"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="运营登录手机号:"
              :prop="'list.' + index + '.phone'"
              :rules="{
                required: true,
                message: '运营登录手机号不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.phone"
                placeholder="输入手机号"
                style="width:180px;"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="充值方式:"
              :prop="'list.' + index + '.rechargeType'"
              :rules="{
                required: true,
                message: '充值方式不能为空',
                trigger: 'blur'
              }"
            >
              <el-select v-model="item.rechargeType" placeholder="选择成本类型">
                <el-option label="线上" value="线上"></el-option>
                <el-option label="线下" value="线下"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              label="摘要:"
              :prop="'list.' + index + '.remark'"
              :rules="{
                required: false,
                message: '摘要不能为空',
                trigger: 'blur'
              }"
            >
              <el-input v-model="item.remark" style="width:300px;"></el-input>
            </el-form-item>
            <el-form-item
              label="初期数量:"
              :prop="'list.' + index + '.originalCount'"
              :rules="{
                required: item.rechargeType == '线上',
                message: '初期数量不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model.number="item.originalCount"
                style="width:130px;"
              ></el-input>
            </el-form-item>
            <!-- <el-form-item
              label="余额数量:"
              :prop="'list.' + index + '.balanceCount'"
              :rules="{
                required: item.rechargeType == 1,
                message: '余额数量不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model.number="item.balanceCount"
                style="width:130px;"
              ></el-input>
            </el-form-item> -->
            <div class="tit">本期增加额:</div>
            <el-form-item
              label="充值金额:"
              :prop="'list.' + index + '.rechargeMoney'"
              :rules="{
                required: true,
                message: '充值金额不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.rechargeMoney"
                style="width:130px;"
              ></el-input>
              元
            </el-form-item>
            <el-form-item
              label="充值数量:"
              :prop="'list.' + index + '.rechargeCount'"
              :rules="{
                required: true,
                message: '充值数量不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.rechargeCount"
                style="width:130px;"
              ></el-input>
              个
            </el-form-item>
            <el-form-item
              label="赠送数量:"
              :prop="'list.' + index + '.giveCount'"
              :rules="{
                required: true,
                message: '赠送数量不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.giveCount"
                style="width:130px;"
              ></el-input>
              个
            </el-form-item>
            <div class="tit">本期减少额:</div>
            <el-form-item
              label="日常扶持刷币:"
              :prop="'list.' + index + '.dailyBrushCoin'"
              :rules="{
                required: true,
                message: '日常扶持刷币不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.dailyBrushCoin"
                style="width:130px;"
              ></el-input>
              个
            </el-form-item>
            <el-form-item
              label="针对性扶持刷币:"
              :prop="'list.' + index + '.pointBrushCoin'"
              :rules="{
                required: true,
                message: '针对性扶持刷币不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.pointBrushCoin"
                style="width:130px;"
              ></el-input>
              个
            </el-form-item>
            <el-form-item
              label="招募主播刷币:"
              :prop="'list.' + index + '.anchorBrushCoin'"
              :rules="{
                required: true,
                message: '招募主播刷币不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.anchorBrushCoin"
                style="width:130px;"
              ></el-input>
              个
            </el-form-item>
            <el-form-item
              label="其他情况刷币:"
              :prop="'list.' + index + '.otherBrushCoin'"
              :rules="{
                required: true,
                message: '其他情况刷币不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.otherBrushCoin"
                style="width:130px;"
              ></el-input>
              个
            </el-form-item>
            <el-form-item
              label="刷币总量:"
              :prop="'list.' + index + '.totalBrushCoin'"
              :rules="{
                required: true,
                message: '刷币总量不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.totalBrushCoin"
                style="width:130px;"
              ></el-input>
              个
            </el-form-item>
            <el-form-item
              label="余额数量:"
              :prop="'list.' + index + '.balanceCount'"
              :rules="{
                required: item.rechargeType == '线上',
                message: '余额数量不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.balanceCount"
                style="width:130px;"
              ></el-input>
              个
            </el-form-item>
            <br />
            <el-form-item
              label="公会分成比例:"
              :prop="'list.' + index + '.publicRate'"
              :rules="{
                required: true,
                message: '公会分成比例不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.publicRate"
                style="width:130px;"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="刷币工会分成:"
              :prop="'list.' + index + '.brushPublic'"
              :rules="{
                required: true,
                message: '刷币工会分成不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.brushPublic"
                style="width:130px;"
              ></el-input>
              元
            </el-form-item>
            <br />

            <el-form-item
              label="针对性扶持主播ID:"
              :prop="'list.' + index + '.pointAnchorNo'"
              :rules="{
                required:
                  item.pointAnchorNo ||
                  item.pointAnchorNick ||
                  item.expectBackMoney,
                message: '针对性扶持主播ID不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.pointAnchorNo"
                style="width:130px;"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="针对性扶持主播昵称:"
              :prop="'list.' + index + '.pointAnchorNick'"
              :rules="{
                required:
                  item.pointAnchorNo ||
                  item.pointAnchorNick ||
                  item.expectBackMoney,
                message: '昵称不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.pointAnchorNick"
                style="width:130px;"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="预计主播返还金额:"
              :prop="'list.' + index + '.expectBackMoney'"
              :rules="{
                required:
                  item.pointAnchorNo ||
                  item.pointAnchorNick ||
                  item.expectBackMoney,
                message: '预计主播返还金额不能为空',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.expectBackMoney"
                style="width:130px;"
              ></el-input>
              元
            </el-form-item>
            <!-- <el-upload
              class="diy-uploadBtn"
              :action="uploadImgAjax.config.url"
              :headers="uploadImgAjax.config.headers"
              name="file"
              ref="uploadImg"
              accept=".jpg, .gif, .jpeg, .png"
              :show-file-list="false"
              :on-success="rUploadImgSuc"
              :on-error="rUploadImgFail"
              :before-upload="rUploadImgBefore"
            >
              <el-button type="primary" @click="rUploadImgbtn(index)"
                >上传截图</el-button
              >
            </el-upload>

            <div class="img-box">
              <div class="img" v-for="(v, i) in item.picPath" :key="i">
                <i
                  class="el-icon-circle-close icon"
                  @click="rDeleteUploadImg(index, i)"
                ></i>
                <el-image
                  class="image"
                  :preview-src-list="item.picPath"
                  :z-index="i"
                  :src="v"
                  fit="cover"
                ></el-image>
              </div>
            </div> -->
          </div>
        </template>
      </el-form>
      <div class="file-box" v-if="this.ajaxData.list.length"></div>
      <div class="footer" v-if="this.ajaxData.list.length">
        <el-button type="primary" @click="submitForm('form')">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
// 校验规则
// 当充值方式为“线下”时，日期、平台、币别、币别兑换比例、充值金额、充值系数、实际到账额、
//（日常扶持刷币、针对性扶持刷币、招募主播刷币、其它情况刷币，不能都为空）、刷币总额、公会分成比例、刷币公会分成为必填项，点击“提交时校验”，提示“数据X的XX不能为空”

// 当充值方式为“线上”时，日期、平台、币别、币别兑换比例、平台账号、期初余额、充值余额、充值系数、实际到账金额、
//（日常扶持刷币、针对性扶持刷币、招募主播刷币、其它情况刷币，不能都为空），刷币总额、本期余额、公会分成比例、刷币公会分成都为必填项，点击“提交时校验”，提示“数据X的XX不能为空”

//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
// import { deepClone } from "@/utils";
import UploadExcelComponent from "@/components/UploadExcel/index.vue";
// import excelMap from "../map.js";
import { addOrUpdateCheck } from "@/api/finance";
// import { getOssParam } from "@/api/others";
const currentCorporation = JSON.parse(
  localStorage.getItem("currentCorporation")
);
let localSid = localStorage.getItem("sid");
let sid = localSid ? JSON.parse(localSid) : {};
const platformMap = [
  "抖音",
  "bilibili",
  "虎牙",
  "YY",
  "NOW",
  "繁星",
  "一直播",
  "陌陌",
  "全民K歌",
  "悠趣"
];

export default {
  name: "",
  //import引入的组件需要注入到对象中才能使用
  components: { UploadExcelComponent },
  props: {
    excelMap: {
      type: Object
    }
  },
  data() {
    //这里存放数据
    return {
      uploadImportAjax: {
        loading: false,
        config: {
          disabled: false,
          headers: {
            Authorization: "bearer " + sid.access_token
          },
          data: {
            tenantId: currentCorporation.id
          },
          url: "/bs/cost/brush/importExcel"
        }
      },
      platformMap,
      form: {},
      // 上传图片对应表单下标
      upLoadImgIndex: "",
      // excelMap,
      ajaxData: {
        checkName: "",
        list: []
      },
      upLoadData: "",
      excelPath: [],
      uploadImgAjax: {
        loading: false,
        config: {
          disabled: false,
          headers: {},
          url: ""
        }
      }
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (isLt1M) {
        return true;
      }
      console.log("results", file);
      if (!file.xx) {
        return;
      }
      this.$message({
        message: "Please do not upload files larger than 1m in size.",
        type: "warning"
      });
      return false;
    },
    uploadImportSuc(respData) {
      let _that = this;
      _that.uploadImportAjax.loading.close();
      if (respData.code === this.STATUS.success[0]) {
        // this.excelPath.push(respData.data.fileUrl);
        _that.pageAjax.data.list = this.pageAjax.data.list.concat(
          respData.data
        );
      } else {
        _that.$message.error({
          message: respData.msg || "上传失败"
        });
      }
    },
    uploadImportFail() {
      let _that = this;
      _that.uploadImportAjax.loading.close();
      _that.uploadImportAjax.config.disabled = false;
      _that.$message.error({
        message: "上传错误，请查看网络或联系管理员",
        onClose() {}
      });
    },
    uploadImportBefore() {
      this.uploadImportAjax.loading = this.$loading({
        text: "上传中。。。",
        lock: true
      });
      // this.upLoadData.key = "2020-04-21/" + file.name;
    },
    handleSuccess({ results }) {
      results.shift();
      const arr = results.map(v => {
        const data = [];
        const excelMap = this.excelMap;
        const result = {};
        for (let i in v) {
          data.push(v[i]);
        }
        for (let i in data) {
          result[excelMap[i]] = data[i];
        }
        result.time = result.time.replace(/\//gi, "-");
        result.time = result.time.split("~");
        result.actualArrival = 0;
        result.picPath = "123,3434";
        console.log(result);

        return result;
      });
      this.ajaxData.list = this.ajaxData.list.concat(arr);
      // this.tableData = results;
      // this.tableHeader = header;昨天睡了好多
    },
    rUploadSuc(res) {
      console.log(res);
    },
    /* 上传图片 */
    rUploadImgSuc(respData, file, fileList) {
      let _that = this;
      _that.uploadImgAjax.config.disabled = false;
      _that.uploadImgAjax.loading.close();

      if (respData.code === _that.STATUS.success[0]) {
        // this.excelPath.push(respData.data.fileUrl);
        const path = [];
        fileList.forEach(v => {
          path.push(v.response.data.fileUrl);
        });
        this.excelPath = path;
      } else {
        _that.$message.error({
          message: respData.msg || "上传失败",
          onClose() {}
        });
      }
    },
    rUploadImgFail() {
      let _that = this;
      _that.uploadImgAjax.loading.close();
      _that.uploadImgAjax.config.disabled = false;
      _that.$message.error({
        message: "上传错误，请查看网络或联系管理员",
        onClose() {}
      });
    },
    handleChange(file, fileList) {
      console.log(file, fileList);
      const path = [];
      fileList.forEach(v => {
        path.push(v.response.data.fileUrl);
      });
      console.log(path);

      this.excelPath = path;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      const path = [];
      fileList.forEach(v => {
        path.push(v.response.data.fileUrl);
      });
      this.excelPath = path;
    },
    rUploadImgbtn(index) {
      this.upLoadImgIndex = index;
    },
    rUploadImgBefore() {
      let _that = this;
      _that.uploadImgAjax.loading = this.$loading({
        text: "上传中。。。",
        lock: true
      });
    },
    upLoadBefore(file) {
      console.log(file);
      this.upLoadData.key = "2020-04-21/" + file.name;
    },
    rDeleteUploadImg(fromIndex, imgIndex) {
      this.ajaxData.list[fromIndex].picPath.splice(imgIndex, 1);
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.ajaxData.list = this.ajaxData.list.map(v => {
            v.beginTime = v.time[0];
            v.endTime = v.time[1];
            return v;
          });
          const data = {
            brushCoinVoList: this.ajaxData.list,
            excelPath: this.excelPath.join(),
            checkName: this.ajaxData.checkName
          };
          addOrUpdateCheck(data).then(res => {
            console.log(res);
            if (res.data.code === this.STATUS.success[0]) {
              this.$message.success("提交成功");
              this.cancel();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    addFrom() {
      const initdata = {
        time: [],
        actualArrival: "123", //实际到账金额
        anchorBrushCoin: "", //招募主播刷币
        balanceCount: "", //余额数量
        beginTime: "", //开始日期
        brushPublic: "", //刷币公会分成
        // checkNo: "", //审核单号
        // checkStatus: 0, //审核状态->1.待审核；2.审核通过
        // coinRate: 0, //币别兑换比例
        coinType: "", //币别
        dailyBrushCoin: "", //日常扶持刷币
        endTime: "", //结束时间
        expectBackMoney: "", //预计主播返还金额
        giveCount: "", //赠送数量
        // id: 0, //核销ID
        originalCount: "", //期初数量
        otherBrushCoin: "", //其他情况刷币
        phone: "", //运营手机号
        // picPath: "", //图片截图路径
        platform: "", //平台
        platformAccount: "", //平台账号
        pointAnchorNick: "", //针对性扶持主播昵称
        pointAnchorNo: "", //针对性扶持主播号
        pointBrushCoin: "", //针对性扶持刷币
        publicRate: "", //公会分成比例
        rechargeCount: "", //充值数量
        rechargeMoney: "", //充值金额
        rechargeRate: "", //充值系数
        rechargeType: "线上", //充值方式->1.线上；2.线下
        remark: "", //摘要
        totalBrushCoin: "", //刷币总额
        username: "" //运营姓名
      };
      this.ajaxData.list.push(initdata);
    },
    delFrom(index) {
      this.ajaxData.list.splice(index, 1);
      if (this.ajaxData.list.length === 0) {
        this.excelPath = [];
      }
    },
    cancel() {
      this.ajaxData.list = [];
      this.excelPath = [];
      this.$refs["form"].clearValidate();
      this.$emit("cancel");
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    // 默认添加一个
    // getOssParam().then(res => {
    //   console.log(res);
    //   this.uploadImgAjax.config.url = res.data.data.host;
    //   this.upLoadData = res.data.data;
    //   this.upLoadData.OSSAccessKeyId = res.data.data.accessid;
    // });
    // this.addFrom();
    // this.uploadImgAjax.loading.close();
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类
.page {
  position: absolute;
  top: 15px;
  right: 15px;
  bottom: 15px;
  left: 15px;
  padding-top: 60px;
  .top {
    height: 50px;
    width: 100%;
    box-sizing: border-box;
    padding: 15px;
    position: absolute;
    top: 0;
    left: 0;
  }

  .form {
    height: calc(100% - 60px);
    width: 100%;
    position: absolute;
    top: 60px;
    left: 0;
    overflow: auto;
    padding: 15px;
    box-sizing: border-box;
  }
}
.file-box {
  width: 500px;
}
.tit {
  font-weight: bold;
  color: #333;
  padding-bottom: 10px;
}
.image {
  width: 100%;
  height: 100%;
}
.img {
  width: 260px;
  height: 500px;
  background: #ddd;
  margin-right: 15px;
  margin-bottom: 15px;
  position: relative;
  display: inline-block;
  .icon {
    font-size: 30px;
    position: absolute;
    top: 5px;
    right: 5px;
    z-index: 1;
    cursor: pointer;
  }
}
.img-box {
  margin: 20px 0;
}
.footer {
  text-align: center;
}
.list {
  padding-top: 15px;
  border-top: 1px solid #ddd;
}
</style>
<style lang="scss">
.img-box {
  .el-icon-circle-close {
    color: #fff;
  }
}
</style>
